package org.zhxy.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.zhxy.model.constant.CaptchaConstant;
import org.zhxy.model.constant.JWTConstant;
import org.zhxy.model.constant.UserTypeConstant;
import org.zhxy.model.context.LoginContextHolder;
import org.zhxy.model.entity.Admin;
import org.zhxy.model.entity.Student;
import org.zhxy.model.entity.Teacher;
import org.zhxy.model.exception.BizException;
import org.zhxy.model.request.LoginRequest;
import org.zhxy.service.AdminService;
import org.zhxy.service.StudentService;
import org.zhxy.service.SystemService;
import org.zhxy.service.TeacherService;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SystemServiceImpl implements SystemService {
    private final AdminService adminService;
    private final TeacherService teacherService;
    private final StudentService studentService;

    // 获取图形验证码
    @Override
    public void getCaptcha(HttpSession httpSession, HttpServletResponse response) throws IOException {
        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(CaptchaConstant.WIDTH, CaptchaConstant.HEIGHT, CaptchaConstant.CODE_COUNT, CaptchaConstant.LINE_COUNT);
        // 将验证码保存到 session
        httpSession.setAttribute("captcha", lineCaptcha.getCode());
        // 写出验证码图片
        lineCaptcha.write(response.getOutputStream());
    }

    // 登录
    @Override
    public String login(LoginRequest loginRequest, HttpSession httpSession) {
        // 校验验证码
        // String captcha = (String) httpSession.getAttribute(CaptchaConstant.SESSION_KEY);
        // if (captcha == null) {
        //     throw new BizException("验证码已失效，请重新获取");
        // }
        // String verifiCode = loginRequest.getVerifiCode();
        // if (!verifiCode.equalsIgnoreCase(captcha)) {
        //     throw new BizException("验证码错误");
        // }
        // 查询用户名
        Admin user = null;
        String name = loginRequest.getUsername();
        switch (loginRequest.getUserType()) {
            case UserTypeConstant.ADMIN:
                user = adminService.findByName(name);
                break;
            case UserTypeConstant.TEACHER:
                user = teacherService.findByName(name);
                break;
            case UserTypeConstant.STUDENT:
                user = studentService.findByName(name);
                break;
        }
        if (user == null) {
            throw new BizException("用户名或密码错误");
        }
        // 校验密码
        String password = loginRequest.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!user.getPassword().equals(password)) {
            throw new BizException("用户名或密码错误");
        }
        // 生成 token
        HashMap<String, Object> payload = new HashMap<>();
        payload.put(JWTConstant.USER_ID, user.getId());
        payload.put(JWTConstant.USER_TYPE, loginRequest.getUserType());
        return JWTUtil.createToken(payload, JWTConstant.SECRET.getBytes(StandardCharsets.UTF_8));
    }

    // 获取用户信息
    @Override
    public Map<String, Object> getUserInfo() {
        Integer userId = LoginContextHolder.getUserId();
        Integer userType = LoginContextHolder.getUserType();
        HashMap<String, Object> map = new HashMap<>();
        map.put("userType", userType);
        // 查询用户

        switch (userType) {
            case UserTypeConstant.ADMIN:
                Admin admin = adminService.getById(userId);
                map.put("user", admin);
                break;
            case UserTypeConstant.TEACHER:
                Teacher teacher = teacherService.getById(userId);
                map.put("user", teacher);
                break;
            case UserTypeConstant.STUDENT:
                Student student = studentService.getById(userId);
                map.put("user", student);
                break;
        }
        return map;
    }

    @Override
    public void updatePwd(String oldPwd, String newPwd) {
        // 获取用户信息
        Integer userId = LoginContextHolder.getUserId();
        Integer userType = LoginContextHolder.getUserType();

        Admin user = null;

        switch (userType) {
            case UserTypeConstant.ADMIN:
                user = adminService.getById(userId);
                validateOldPwd(oldPwd, user);
                adminService.updatePwd(userId, newPwd);
                break;
            case UserTypeConstant.TEACHER:
                user = teacherService.getById(userId);
                validateOldPwd(oldPwd, user);
                teacherService.updatePwd(userId, newPwd);
                break;
            case UserTypeConstant.STUDENT:
                user = studentService.getById(userId);
                validateOldPwd(oldPwd, user);
                studentService.updatePwd(userId, newPwd);
                break;
        }
    }

    private void validateOldPwd(String oldPwd, Admin user) {
        oldPwd = DigestUtils.md5DigestAsHex(oldPwd.getBytes());

        if (user == null || !user.getPassword().equals(oldPwd)) {
            throw new BizException("旧密码错误");
        }
    }
}
